﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
using EMC;
using System.Threading;

namespace Server
{
    class Files
    {
        private Socket clientSocket;
        //private string downloadTo;
        private int bufferSize;
        private string[] action;
        private byte[] buffer;
        private FileManagement fileMan;
        private Dictionary<string, string> options;
        //private string mess;

        public Files(Dictionary<string, string> Options)
        {
            options = Options;
        }

        public Files(Socket clientsock, Dictionary<string, string> Options)
        {
            options = Options;
            clientSocket = clientsock;
            bufferSize = 1000;
            buffer = new byte[bufferSize];
            string dbConfigFile = @"./db_settings.xml";
            databaseConfiguration config = new databaseConfiguration(dbConfigFile);
            fileMan = new FileManagement(config);
        }

        public void handle(object FileSocket)
        {
            Socket clientSocket = (Socket)FileSocket;
            Thread.Sleep(100);
            sendMessage(clientSocket,"FFFFUUUUUUUUCCCCCKKKKK");
            //while (true)
            //{
            //    recMess(clientSocket);

            //}
            
        }

        private string recMess(Socket incomming)
        {
            byte[] buffer = new byte[1024];

            try
            {
                incomming.Receive(buffer);
                System.Diagnostics.Debug.WriteLine("Message Recived on FileSocket: " + Encoding.UTF8.GetString(buffer));
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err);
            }

            return Encoding.UTF8.GetString(buffer);
        }

        public string handleFile(string[] message)
        {
            action = message;
            string ret = null;
            //Dictionary<string, string> fileDictionary = convertProcotcolToDictionary(message);

            if (message[2] == "UPLOAD")
            {
                sendMessage(clientSocket, "$FRANK,FILE,UPLOAD,START,");
                data(message);
                sendMessage(clientSocket, "$FRANK,FILE,UPLOAD,END,");
                //fileMan.addfile(fileDictionary["NAME"], fileDictionary["DESC"], fileDictionary["USER"]);

            }
            else if (message[2] == "DOWNLOAD")
            {
                sendMessage(clientSocket, "$FRANK,FILE,DOWNLOAD,START,");
                data(message);
                sendMessage(clientSocket, "$FRANK,FILE,DOWNLOAD,END,");

            }
            return ret;
        }



        private bool data(string[] message)
        {

            if (message[2] == "UPLOAD")
            {
                FileStream filedata = new FileStream(options["Projects_Path"] + "\\" + message[3], FileMode.Append, FileAccess.Write);
                Thread.Sleep(100);
                int receivedBytesLen = 0;
                bool crap = true;
                do
                {
                    receivedBytesLen = clientSocket.Receive(buffer);
                    Thread.Sleep(10);
                    System.Diagnostics.Debug.WriteLine(receivedBytesLen);
                    filedata.Write(buffer, 0, bufferSize);
                    if (receivedBytesLen != bufferSize) { crap = false; }
                    //} while (receivedBytesLen != 1000);
                } while (crap == true);
                System.Diagnostics.Debug.WriteLine("Completed");
                filedata.Flush();
                filedata.Close();

            }
            else if (message[2] == "DOWNLOAD")
            {
                FileStream filedata = new FileStream(options["Projects_Path"] + message[3], FileMode.Open, FileAccess.Read);

                buffer = new byte[bufferSize];
                int count;

                while ((count = filedata.Read(buffer, 0, bufferSize)) > 0)
                {

                    System.Diagnostics.Debug.WriteLine(clientSocket.Send(buffer, count, SocketFlags.None));
                }

                System.Diagnostics.Debug.WriteLine("file: " + message[3] + " has been sent");
            }
            else if (message[3] == "LIST")
            {
                //fileMan.
            }

            return true;
        }

        private void sendMessage(Socket clientSocket, string protocolMessage)
        {
            try
            {

                byte[] sendmess = Encoding.UTF8.GetBytes(protocolMessage);

                System.Diagnostics.Debug.WriteLine("File Socket sent: " + protocolMessage);

                clientSocket.Send(sendmess);
                sendmess = null;


            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err);

            }

        }
    }
}

